<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <meta http-equiv="Pragma" content="no-cache" />
    <title>付款</title>
    <link rel="stylesheet" href="css/weui.min.css" />
    <link rel="stylesheet" href="fonts/iconfont.css" />
    <link rel="stylesheet" href="css/style.css" />
    <link rel="stylesheet" href="css/payment.css" />
    <script src="js/jquery-2.2.3.min.js"></script>
    <link rel="stylesheet" href="https://cdn.bootcss.com/weui/1.1.2/style/weui.min.css">
    <link rel="stylesheet" href="https://cdn.bootcss.com/jquery-weui/1.2.0/css/jquery-weui.min.css">
    <!-- <script src="js/weui.min.js"></script> -->

</head>
<style>
</style>
<body ontouchstart>

    <div class="weui-content">
        <!-- <div style="width:100%;height:100%;position:fixed;top:0px;left:100%;z-index:4;"></div> -->
        <div class="payment-title">请输入金额</div>
        <div class="input-wrapper">
            <input class="payment-box" type="text" id="price">
        </div>
        <div id="purse-balance"> 钱包余额</div>
        <div id="welfare-cash">
            <span>福利金:
                <span id="welfare">0</span>
                元
            </span>
            <span style="float:right;">
                现金:
                <span id="cash"> 0</span>
                元
            </span>
        </div>
        <div style="margin:auto;width:354px;">
            <button id="submit">
                确认支付
            </button>
        </div>
    </div>
</body>
<script src="./api.js"></script>
<script src="https://cdn.bootcss.com/jquery-weui/1.2.0/js/jquery-weui.min.js"></script>
<script>
    window.onload = function () {

        let api = getApi()
        if (localStorage.getItem('wxUserInfo')) {
            let userinfo = JSON.parse(localStorage.getItem('wxUserInfo')).data
            let customerID = userinfo.customer.customerID
            customerID = Number(customerID)

            //获取本地缓存token
            let token = userinfo.token

            //获取福利金 现金
            function getAccountAmount() {
                fetch(api + '/customer/' + customerID, {
                    method: "get",
                    headers: {
                        'Content-type': 'application/json',
                        "Authorization": token
                    }
                })
                    .then(res => {
                        if (res.status == 401) {
                            alert('token过期，请重新登录')
                            location.href = './index.html';
                        }
                        return res;
                    })
                    .then(res => res.json())
                    .then((data) => {
                        // 福利金
                        let welfare = data.data.welfare
                        //现金
                        let cash = data.data.cash
                        //总余额
                        let totalBalance = data.data.welfare + data.data.cash

                        $('#cash').html(cash)
                        $('#welfare').html(welfare)

                    }).catch((err) => {
                        window.location.href = './index.html'
                    })
            }

            //调用获取福利金
            getAccountAmount()

            // 获取url及参数
            let windowIDstr = window.location.href.split('?')[1]
            if (windowIDstr.indexOf('price') != -1) {

                // ==========输入框不可以编辑=============
                $('.weui-content').css('display', 'none');
                let paramsArry = windowIDstr.split('&')
                let windowID = paramsArry[0].split('=')[1]
                windowID = Number(windowID)
                let price = paramsArry[1].split('=')[1]
                price = Number(price)
                let orderID = paramsArry[2].split('=')[1]
                $('#price').val(price)
                $('#price').attr('disabled', true)
                
                //点击确认支付
                    let data = {
                        customerID: customerID,
                        windowID: windowID,
                        price: price,
                        orderID: orderID
                    }

                    //发起支付请求
                    fetch(`${api}/consumingRecord/scan`, {
                        method: "POST",
                        headers: {
                            'Content-type': 'application/json',
                            "Authorization": token
                        },
                        body: JSON.stringify(data)
                    })
                        .then(res => res.json())
                        .then((data) => {
                            console.log(data)
                            if (data.data.state == true) {
                                $.alert("支付成功", "支付提示", function () {
                                    //点击确认后的回调函数
                                    window.location.href = './zhanghu.html'
                                });
                            } else {
                                
                                $('.weui-content').css('display', 'block');
                                $('.payment-title').text("账户余额不足，请支付")
                                $('.payment-title').css({"width":"100%","font-size":"16px"})
                                let price = new Number(data.data.consumingRecord.price).toFixed(2);
                                $('#price').val(price);
                                $('#price').css("border","none");
                                let customerID = data.data.consumingRecord.customerID;
                                let windowID = data.data.consumingRecord.windowID;
                                $('#submit').on('click', function(){
                                     let params = {
                                        "trade_type": "1",
                                        "orderno": "",
                                        "customerID": customerID,
                                        "body": "微信公众号消费",
                                        "total_fee": price,
                                        "product_id": "",
                                        "total_fee_type": "2",
                                        'windowID': windowID,
                                        'orderID': orderID
                                    }


                                    fetch(`${api}/unifiedorder`, {
                                        method: "post",
                                        headers: {
                                            'Content-type': 'application/json',
                                            "Authorization": token
                                        },
                                        body: JSON.stringify(params)
                                    })
                                        .then(res => res.json())
                                        .then(payParams => {
                                            let appId = payParams.appId
                                            let timeStamp = payParams.timeStamp
                                            let nonceStr = payParams.nonceStr
                                            let package = payParams.package
                                            let signType = payParams.signType
                                            let paySign = payParams.paySign

                                            function onBridgeReady() {
                                                console.log(appId, timeStamp, nonceStr, package, signType, paySign)
                                                WeixinJSBridge.invoke(
                                                    'getBrandWCPayRequest', {
                                                        "appId": appId,//公众号名称，由商户传入     
                                                        "timeStamp": timeStamp,//时间戳，自1970年以来的秒数     
                                                        "nonceStr": nonceStr,//随机串     
                                                        "package": package,
                                                        "signType": signType,//微信签名方式：     
                                                        "paySign": paySign //微信签名 
                                                    },
                                                    function (res) {
                                                        $('.tips').html(res)
                                                        if (res.err_msg == "get_brand_wcpay_request:ok") {
                                                            // 使用以上方式判断前端返回,微信团队郑重提示：
                                                            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                                                            location.href = './zhanghu.html';
                                                        } else {
                                                            alert('支付失败')
                                                        }
                                                    });
                                            }
                                            if (typeof WeixinJSBridge == "undefined") {
                                                if (document.addEventListener) {
                                                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                                                } else if (document.attachEvent) {
                                                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                                                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                                                }
                                            } else {
                                                onBridgeReady();
                                            }
                                        })
                                        .catch(err => {
                                            console.log(err)
                                        })
                                })
                            }
                        }).catch((err) => {
                            alert('支付失败')
                        })
                // })
            } else {
                //=============输入框可以编辑=============
                //点击确认支付
                $('#submit').on('click', function () {
                    let windowID = windowIDstr.split('=')[1]
                    windowID = Number(windowID)
                    let price = $('#price').val()
                    price = Number(price)
                    let data = {
                        customerID: customerID,
                        windowID: windowID,
                        price: price,
                        orderID: '',
                        note: ''
                    }
                    
                    //发起支付请求
                    fetch(`${api}/consumingRecord/scan`, {
                        method: "POST",
                        headers: {
                            'Content-type': 'application/json',
                            "Authorization": token
                        },
                        body: JSON.stringify(data)
                    })
                        .then(res => res.json())
                        .then((data) => {
                            let orderID = data.data.consumingRecord.orderID
                            if (data.data.state == true) {
                                $.alert("支付成功", "支付提示", function () {
                                    //点击确认后的回调函数
                                    window.location.href = './zhanghu.html'
                                });
                            } else {
                                let price = new Number(data.data.consumingRecord.price).toFixed(2);
                                let customerID = data.data.consumingRecord.customerID;
                                let windowID = data.data.consumingRecord.windowID;
                                // 询问是否微信消费
                                $.confirm(`账户余额不足，需微信支付${price}元`, function () {
                                    let params = {
                                        "trade_type": "1",
                                        "orderno": '',
                                        "orderID": orderID,
                                        "customerID": customerID,
                                        "body": "微信公众号消费",
                                        "total_fee": price,
                                        "product_id": "",
                                        "total_fee_type": "2",
                                        'windowID': windowID
                                    }


                                    fetch(`${api}/unifiedorder`, {
                                        method: "post",
                                        headers: {
                                            'Content-type': 'application/json',
                                            "Authorization": token
                                        },
                                        body: JSON.stringify(params)
                                    })
                                        .then(res => res.json())
                                        .then(payParams => {
                                            let appId = payParams.appId
                                            let timeStamp = payParams.timeStamp
                                            let nonceStr = payParams.nonceStr
                                            let package = payParams.package
                                            let signType = payParams.signType
                                            let paySign = payParams.paySign

                                            function onBridgeReady() {
                                                console.log(appId, timeStamp, nonceStr, package, signType, paySign)
                                                WeixinJSBridge.invoke(
                                                    'getBrandWCPayRequest', {
                                                        "appId": appId,//公众号名称，由商户传入     
                                                        "timeStamp": timeStamp,//时间戳，自1970年以来的秒数     
                                                        "nonceStr": nonceStr,//随机串     
                                                        "package": package,
                                                        "signType": signType,//微信签名方式：     
                                                        "paySign": paySign //微信签名 
                                                    },
                                                    function (res) {
                                                        $('.tips').html(res)
                                                        if (res.err_msg == "get_brand_wcpay_request:ok") {
                                                            // 使用以上方式判断前端返回,微信团队郑重提示：
                                                            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                                                            location.href = './zhanghu.html';
                                                        } else {
                                                            alert('支付失败')
                                                        }
                                                    });
                                            }
                                            if (typeof WeixinJSBridge == "undefined") {
                                                if (document.addEventListener) {
                                                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                                                } else if (document.attachEvent) {
                                                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                                                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                                                }
                                            } else {
                                                onBridgeReady();
                                            }
                                        })
                                        .catch(err => {
                                            console.log(err)
                                        })
                                }, function () {
                                    //点击取消后的回调函数
                                    return;
                                });
                            }
                        }).catch((err) => {
                            alert(err)
                        })
                })
            }
        } else {
            alert('请先登录')
            window.location.href = './index.html'
        }
    }
</script>

</html>